package com.luhuiguo.cms.client.presenter;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.luhuiguo.cms.client.GlobalConstants;
import com.luhuiguo.cms.client.GlobalMessages;
import com.luhuiguo.cms.client.ui.EditAttachmentView;
import com.luhuiguo.cms.shared.event.AddAttachmentEvent;
import com.luhuiguo.cms.shared.event.AddAttachmentEventHandler;
import com.luhuiguo.cms.shared.event.AttachmentUploadedEvent;
import com.luhuiguo.cms.shared.event.AttachmentUploadedEventHandler;
import com.luhuiguo.cms.shared.event.AttachmentsDeletedEvent;
import com.luhuiguo.cms.shared.event.AttachmentsDeletedEventHandler;
import com.luhuiguo.cms.shared.model.AttachmentModel;
import com.luhuiguo.cms.shared.rpc.RemoveAttachments;
import com.luhuiguo.cms.shared.rpc.RemoveAttachmentsResult;
import com.luhuiguo.gwt.dispatcher.client.DispatcherAsync;
import com.luhuiguo.gwt.presenter.client.EventBus;
import com.luhuiguo.gwt.presenter.client.widget.WidgetContainerDisplay;
import com.luhuiguo.gwt.presenter.client.widget.WidgetContainerPresenter;

public class AttachmentsPresenter extends WidgetContainerPresenter<AttachmentsPresenter.Display> {

    public interface Display extends WidgetContainerDisplay {

        Button getAddButton();

        Button getDeleteButton();

        Grid<BeanModel> getGrid();

        EditAttachmentView getEditAttachmentView();

        void reloadData();
    }

    private DispatcherAsync dispatcher;

    @SuppressWarnings("unused")
    private GlobalConstants constants;

    private GlobalMessages messages;

    private EditAttachmentPresenter editAttachmentPresenter;

    private Long articleId;

    @Inject
    public AttachmentsPresenter(Display display, EventBus eventBus, DispatcherAsync dispatcher,
            GlobalConstants constants, GlobalMessages messages, EditAttachmentPresenter editAttachmentPresenter) {
        super(display, eventBus, editAttachmentPresenter);
        this.dispatcher = dispatcher;
        this.constants = constants;
        this.messages = messages;

        this.editAttachmentPresenter = editAttachmentPresenter;

    }

    @Override
    protected void onBind() {
        GWT.log("binding AttachmentsPresenter");

        super.onBind();

        registerHandler(eventBus.addHandler(AddAttachmentEvent.TYPE, new AddAttachmentEventHandler() {
            @Override
            public void onAddAttachment(AddAttachmentEvent event) {
                showAddAttachment(event.getArticleId());
            }
        }));

        // registerHandler(eventBus.addHandler(EditAttachmentEvent.TYPE, new
        // EditAttachmentEventHandler() {
        // @Override
        // public void onEditAttachment(EditAttachmentEvent event) {
        // showEditAttachment(event.getAttachmentId());
        // }
        //
        // }));

        registerHandler(eventBus.addHandler(AttachmentUploadedEvent.TYPE, new AttachmentUploadedEventHandler() {
            @Override
            public void onAttachmentUploaded(AttachmentUploadedEvent event) {
                display.reloadData();
                Info.display(messages.success(), messages.attachmentUploaded(event.getFilename()));
            }
        }));

        registerHandler(eventBus.addHandler(AttachmentsDeletedEvent.TYPE, new AttachmentsDeletedEventHandler() {
            @Override
            public void onAttachmentsDeleted(AttachmentsDeletedEvent event) {
                display.reloadData();
                Info.display(messages.success(), messages.attachmentDeleted(event.getAttachments().size()));
            }
        }));

        display.getAddButton().addSelectionListener(new SelectionListener<ButtonEvent>() {
            @Override
            public void componentSelected(ButtonEvent ce) {
                eventBus.fireEvent(new AddAttachmentEvent(articleId));
            }
        });

        display.getDeleteButton().addSelectionListener(new SelectionListener<ButtonEvent>() {
            @Override
            public void componentSelected(ButtonEvent ce) {
                removeAttachments();
            }
        });

        // display.getGrid().addListener(Events.RowDoubleClick, new
        // Listener<GridEvent<BeanModel>>() {
        // public void handleEvent(GridEvent<BeanModel> se) {
        // AttachmentModel m = se.getModel().getBean();
        // eventBus.fireEvent(new EditAttachmentEvent(m.getId()));
        // }
        // });

        display.getGrid().getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {

            @Override
            public void selectionChanged(SelectionChangedEvent<BeanModel> se) {

                if (se.getSelection().size() > 0) {
                    display.getDeleteButton().setEnabled(true);
                } else {
                    display.getDeleteButton().setEnabled(false);
                }
            }
        });

    }

    // protected void showEditAttachment(final Long attachmentId) {
    // dispatcher.execute(new GetAttachment(attachmentId), new
    // AsyncCallback<GetAttachmentResult>() {
    // @Override
    // public void onFailure(Throwable caught) {
    // GWT.log(messages.loadAttachmentFailed(attachmentId), caught);
    // MessageBox.alert(messages.error(),
    // messages.loadAttachmentFailed(attachmentId), null);
    // }
    //
    // @Override
    // public void onSuccess(GetAttachmentResult result) {
    // editAttachmentPresenter.revealDisplay(result.get());
    // }
    // });
    //
    // }

    protected void showAddAttachment(Long articleId) {

        AttachmentModel model = new AttachmentModel();
        model.setArticleId(articleId);
        editAttachmentPresenter.revealDisplay(model);

    }

    protected void removeAttachments() {

        List<BeanModel> models = display.getGrid().getSelectionModel().getSelectedItems();
        final List<Long> list = new ArrayList<Long>();
        for (BeanModel model : models) {
            AttachmentModel a = model.getBean();
            list.add(a.getId());
        }
        final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {
            public void handleEvent(MessageBoxEvent ce) {
                if (Dialog.YES.equals(ce.getButtonClicked().getItemId())) {
                    doRemoveAttachments(list);
                }
            }
        };

        if (list.size() > 0) {
            MessageBox.confirm(messages.confirmDelete(), messages.confirmDeleteAttachments(list.size()), l);
        }
    }

    private void doRemoveAttachments(final List<Long> list) {
        dispatcher.execute(new RemoveAttachments(list), new AsyncCallback<RemoveAttachmentsResult>() {
            public void onFailure(Throwable caught) {
                MessageBox.alert(messages.error(), messages.deleteAttachmentsFailed(), null);
            }

            public void onSuccess(RemoveAttachmentsResult result) {
                eventBus.fireEvent(new AttachmentsDeletedEvent(list));

            }

        });
    }

    @Override
    protected void onRevealDisplay() {
        super.onRevealDisplay();
        display.reloadData();
    }

    public void revealDisplay(Long articleId) {
        this.articleId = articleId;
        revealDisplay();
    }

}
